package beer.zivelin.awesome.walawala.mobile.service;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import com.github.houbb.heaven.util.lang.StringUtil;

import beer.zivelin.awesome.walawala.mobile.entity.ApplicationData;

public class ApplicationHelper {
    public static boolean launch(ApplicationData data, Activity activity) {
        if (activity == null) {
            return false;
        }
        if (StringUtil.isEmpty(data.getPackageName())) {
            return false;
        }
        PackageManager pm = activity.getPackageManager();
        if (pm == null) {
            return false;
        }

        Intent resolveIntent = pm.getLaunchIntentForPackage(data.getPackageName());
        if (resolveIntent == null) {
            return false;
        }
        activity.startActivity(resolveIntent);
        activity.finishAffinity();
        return true;
    }

    public static boolean directToAppDetailsSettings(ApplicationData data, Activity activity) {
        if (activity == null) {
            return false;
        }
        if (StringUtil.isEmpty(data.getPackageName())) {
            return false;
        }
        PackageManager pm = activity.getPackageManager();
        if (pm == null) {
            return false;
        }
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.fromParts("package", data.getPackageName(), null));
        } else {
            return false;
        }
        activity.startActivity(intent);
        return true;
    }
    public static boolean directToAppUninstall(ApplicationData data, Activity activity) {
        if (activity == null) {
            return false;
        }
        if (StringUtil.isEmpty(data.getPackageName())) {
            return false;
        }
        PackageManager pm = activity.getPackageManager();
        if (pm == null) {
            return false;
        }
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction(Intent.ACTION_DELETE);
            intent.setData(Uri.fromParts("package", data.getPackageName(), null));
        } else {
            return false;
        }
        activity.startActivity(intent);
        return true;
    }
}
